//
//  PersonalViewController.m
//  PhotoStudio
//
//  Created by 华谕 on 2017/10/20.
//  Copyright © 2017年 HUYU. All rights reserved.
//

#import "PersonalViewController.h"
#import "RealNameViewController.h"
#import "InformationViewController.h"
#import "SetUpViewController.h"
#import "LoginViewController.h"
#import "HYNavBaseViewController.h"
#import "ReleaseManageViewController.h"
#import "ReturnCarModel.h"
#import "MyCarViewController.h"
#import "ReleaseCarvehicleViewController.h"
#import "MyWalletViewController.h"
#import "ShopDecorationViewController.h"
#import "LineManagementViewController.h"

static NSString *cellPath = @"personCell";
@interface PersonalViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong)UITableView *tableview;
@property (nonatomic, strong)NSArray *titAry;
@property (nonatomic, strong)NSArray *imageAry;
@property (nonatomic, strong)UserAccountModel *model;
@property (nonatomic, strong)ReturnCarModel *returnModel;

@end

@implementation PersonalViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(Successnotice:) name:@"bangdingsuccess" object:nil];
    [self requestUserInfor];
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"bangdingsuccess" object:nil];
}

- (void)Successnotice:(NSNotification *)center
{
    [LTools showMBProgressWithText:@"绑定成功" addToView:sharedDelegate.window];
    [self requestUserInfor];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _titAry = @[@"",@"发布管理",@"钱包",@"设置"];
    _imageAry = @[@"",@"my_sort01",@"my_sort04",@"my_sort05"];
    [self creatUI];
}

- (void)creatUI
{
    self.navigationItem.title = @"我的";
    self.view.backgroundColor = RGB(245, 245, 245);
    self.navigationController.navigationBar.translucent = NO;
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT-TABBAR_HEIGHT-SCREER_HeiX) style:UITableViewStylePlain];
    _tableview.backgroundColor = RGB(245, 245, 245);
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableview];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _titAry.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellPath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = BacksColor;
    if (_model)
    {
        UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, 10*displaywidth, SCREEN_WIDTH, 80*displaywidth)];
        whiteView.backgroundColor = [UIColor whiteColor];
        [cell.contentView addSubview:whiteView];
        if (indexPath.row == 0)
        {
            UIImageView *faceView = [ZCControl createImageViewWithFrame:CGRectMake(15*displaywidth, 10*displaywidth, 60*displaywidth, 60*displaywidth) ImageName:@"morenFace"];
            if (_model.headImg.length > 0)
            {
                [faceView sd_setImageWithURL:URL(_model.headImg) placeholderImage:IMAGE(@"morenFace")];
            }
            faceView.contentMode = UIViewContentModeScaleAspectFill;
            faceView.layer.masksToBounds = YES;
            [whiteView addSubview:faceView];
            UILabel *nameLab = [ZCControl createLabelWithFrame:CGRectMake(90*displaywidth, 15*displaywidth, 80*displaywidth, 25*displaywidth) Font:16.0 Text:_model.username Color:RGB(51, 51, 51)];
            nameLab.lineBreakMode = NSLineBreakByTruncatingTail;
            nameLab.adjustsFontSizeToFitWidth = NO;
            [whiteView addSubview:nameLab];
            UILabel *phoneLab = [ZCControl createLabelWithFrame:CGRectMake(90*displaywidth, 40*displaywidth, SCREEN_WIDTH-90*displaywidth, 25*displaywidth) Font:15.0 Text:string(@"手机号：", _model.phone) Color:RGB(138, 138, 138)];
            [whiteView addSubview:phoneLab];
            NSString *typeStr = @"货主";
            CGFloat w = 30*displaywidth;
            if (_model.type == 1)
            {
                typeStr = @"物流公司";
                w = 40*displaywidth;
            }
            else if (_model.type == 2)
            {
                typeStr = @"司机";
            }
            else if (_model.type == 3)
            {
                typeStr = @"游客";
            }
            UILabel *typeLab = [ZCControl createLabelWithFrame:CGRectMake(175*displaywidth, 20*displaywidth, w, 15*displaywidth) Font:9.0 Text:typeStr Color:[UIColor whiteColor]];
            typeLab.backgroundColor = RGB(255, 153, 0);
            typeLab.layer.cornerRadius = 2;
            typeLab.layer.masksToBounds = YES;
            typeLab.textAlignment = NSTextAlignmentCenter;
            [whiteView addSubview:typeLab];
            NSString *isRZ = @"";
            BOOL k = NO;
            if (_model.isIdentify == 0)
            {
                isRZ = @"未认证";
                k = NO;
            }
            else if (_model.isIdentify == 1)
            {
                isRZ = @"已认证";
                k = YES;
            }
            if (_model.identity)
            {
                if ([_model.identity.status integerValue] == 0)
                {
                    isRZ = @"认证中";
                    k = YES;
                }
                else if ([_model.identity.status integerValue] == 1)
                {
                    isRZ = @"已认证";
                    k = YES;
                }
                else
                {
                    isRZ = @"认证失败";
                    k = NO;
                }
                
            }

            UILabel *idLab = [ZCControl createLabelWithFrame:CGRectMake(180*displaywidth+w, 20*displaywidth, 40*displaywidth, 15*displaywidth) Font:9.0 Text:isRZ Color:[UIColor whiteColor]];
            idLab.backgroundColor = RGB(164, 172, 193);
            idLab.layer.cornerRadius = 2;
            idLab.layer.masksToBounds = YES;
            idLab.textAlignment = NSTextAlignmentCenter;
            [whiteView addSubview:idLab];
            UIButton *rzBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            rzBtn.frame = CGRectMake(SCREEN_WIDTH-90, 15*displaywidth, 50*displaywidth, 50*displaywidth);
            [rzBtn setImage:IMAGE(@"my_sort07") forState:UIControlStateNormal];
            rzBtn.backgroundColor = [UIColor clearColor];
            [rzBtn addTarget:self action:@selector(rzBtnTypeAction) forControlEvents:UIControlEventTouchUpInside];
            rzBtn.hidden = k;
            [whiteView addSubview:rzBtn];
            UIImageView *nextImgView = [ZCControl createImageViewWithFrame:CGRectMake(SCREEN_WIDTH-30*displaywidth, 27.5*displaywidth, 15*displaywidth, 25*displaywidth) ImageName:@"gs_icon07"];
            nextImgView.contentMode = UIViewContentModeScaleAspectFit;
            [whiteView addSubview:nextImgView];
            if (_model.type == 2)
            {
                NSString *imgString = @"mycar-1";
                if ([_model.truck.busy integerValue] == 0)
                {
                    imgString = @"mycar-2";
                }
                
                UIButton *leftBtn = [ZCControl createButtonWithFrame:CGRectMake(15*displaywidth, 100*displaywidth, SCREEN_WIDTH/2-22.5*displaywidth, 45*displaywidth) ImageName:imgString Target:self Action:@selector(busyAction:) Title:nil Font:12.0];
                leftBtn.backgroundColor = [UIColor whiteColor];
                leftBtn.layer.cornerRadius = 4;
                leftBtn.layer.masksToBounds = YES;
                [cell.contentView addSubview:leftBtn];
                NSString *ReturnCar = @"删除回程车";
                UIColor *titcolors = [UIColor whiteColor];
                UIColor *backGroungC = RGB(235, 23, 19);
                if ([_returnModel.shipmentText isEqualToString:@""])
                {
                    ReturnCar = @"发布回程车";
                    titcolors = BlaTitColor;
                    backGroungC = [UIColor whiteColor];
                }
                UIButton *rightBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH/2+7.5*displaywidth, 100*displaywidth, SCREEN_WIDTH/2-22.5*displaywidth, 45*displaywidth) ImageName:nil Target:self Action:@selector(ReturnCarAction:) Title:ReturnCar Font:16.0];
                rightBtn.backgroundColor = backGroungC;
                [rightBtn setTitleColor:titcolors forState:UIControlStateNormal];
                rightBtn.layer.cornerRadius = 4;
                rightBtn.layer.masksToBounds = YES;
                [cell.contentView addSubview:rightBtn];
            }
        }
        else
        {
            whiteView.frame = CGRectMake(0, 10*displaywidth, SCREEN_WIDTH, 50*displaywidth);
            if ([_titAry[indexPath.row] isEqualToString:@"店铺装修"])
            {
                UIImageView *imgAView = [ZCControl createImageViewWithFrame:CGRectMake(SCREEN_WIDTH- 40*displaywidth, 12.5*displaywidth, 25*displaywidth, 25*displaywidth) ImageName:@"my_sort06"];
                imgAView.contentMode = UIViewContentModeScaleAspectFit;
                [whiteView addSubview:imgAView];
            }
            UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(15*displaywidth, 12.5*displaywidth, 25*displaywidth, 25*displaywidth) ImageName:_imageAry[indexPath.row]];
            imgView.contentMode = UIViewContentModeScaleAspectFit;
            [whiteView addSubview:imgView];
            UILabel *titLab = [ZCControl createLabelWithFrame:CGRectMake(60*displaywidth, 10*displaywidth, 150*displaywidth, 30*displayheight) Font:14.0 Text:_titAry[indexPath.row] Color:RGB(51, 51, 51)];
            [whiteView addSubview:titLab];
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
        InformationViewController *vc = [[InformationViewController alloc] init];
        vc.model = _model;
        [self.navigationController pushViewController:vc animated:YES];
    }
    else
    {
        if ([_titAry[indexPath.row] isEqualToString:@"绑定微信"])
        {
            SendAuthReq* req =[[SendAuthReq alloc]init] ;
            req.scope = @"snsapi_userinfo" ;
            req.state = @"Applogin" ;
            //第三方向微信终端发送一个SendAuthReq消息结构
            [WXApi sendReq:req];
        }
        else if ([_titAry[indexPath.row] isEqualToString:@"设置"])
        {
            SetUpViewController *vc = [[SetUpViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        else if ([_titAry[indexPath.row] isEqualToString:@"发布管理"])
        {
            ReleaseManageViewController *vc = [[ReleaseManageViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        else if ([_titAry[indexPath.row] isEqualToString:@"我的货车"])
        {
            MyCarViewController *vc = [[MyCarViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        else if ([_titAry[indexPath.row] isEqualToString:@"钱包"])
        {
            MyWalletViewController *vc = [[MyWalletViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        else if ([_titAry[indexPath.row] isEqualToString:@"店铺装修"])
        {
            if (_model.identity)
            {
                if ([_model.identity.status integerValue] == 0)
                {
                    [LTools showMBProgressWithText:@"实名认证中，请耐心等待，通过后再来装修店铺哦" addToView:self.view];
                    return;
                }
                else if ([_model.identity.status integerValue] == 1)
                {
                    ShopDecorationViewController *vc = [[ShopDecorationViewController alloc] init];
                    [self.navigationController pushViewController:vc animated:YES];
                    return;
                }
                else
                {
                    [LTools showMBProgressWithText:@"实名认证失败，请重新认证，通过后再来装修店铺哦" addToView:self.view];
                    return;
                }
                
            }
            if (_model.isIdentify == 0)
            {
                [LTools showMBProgressWithText:@"请先进行实名认证" addToView:self.view];
                return;
            }
            else if (_model.isIdentify == 1)
            {
                ShopDecorationViewController *vc = [[ShopDecorationViewController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
                return;
            }
            
            
        }
        else if ([_titAry[indexPath.row] isEqualToString:@"线路管理"])
        {
            LineManagementViewController *vc = [[LineManagementViewController alloc] init];
            if ([_model.company.serveName isEqualToString:@"汽运专线"])
            {
                vc.isTrucks = YES;
                vc.isEdit = YES;
            }
            else
            {
                vc.isTrucks = NO;
                if ([_model.company.isEditLine integerValue] == 1)
                {
                    vc.isEdit = YES;
                }
                else
                {
                    vc.isEdit = NO;
                }
            }
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
        if (_model.type == 2)
        {
            return 145*displaywidth;
        }
        return 90*displaywidth;
    }
    return 60*displaywidth;
}

- (void)busyAction:(UIButton *)btn
{
    NSString *busy = @"0";
    if ([_model.truck.busy integerValue] == 0)
    {
        busy = @"1";
    }
    WEAKSELF;
    NSDictionary *dic = @{@"busy":busy};
    [HYBaseHandler requestWithTheFormUrl:SERVER_busySetting Parmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            [weakSelf requestUserInfor];
        }
        else
        {
            
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        
    }];
}

//发布 删除 回程车
- (void)ReturnCarAction:(UIButton *)btn
{
    if (!_model.truck)
    {
        [LTools showMBProgressWithText:@"请先完成货车登记" addToView:self.view];
        return;
    }
    if ([_returnModel.shipmentText isEqualToString:@""])
    {
        //发布
        ReleaseCarvehicleViewController *vc = [[ReleaseCarvehicleViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else
    {
        //删除
        WEAKSELF;
        [HYBaseHandler requestWithTheFormUrl:SERVER_truckClear Parmers:nil Success:^(id obj) {
            if ([obj server_Getcodecheck])
            {
                [weakSelf requestTruckLineMine];
            }
            else
            {
                
                [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
            }
        } failed:^(NSError *error) {
            
        }];
    }
}


- (void)rzBtnTypeAction
{
    RealNameViewController *Vc = [[RealNameViewController alloc] init];
    [self.navigationController pushViewController:Vc animated:YES];
}

- (void)requestTruckLineMine
{
    WEAKSELF;
    [HYBaseHandler requestWithTheFormUrl:SERVER_truckLineMine Parmers:nil Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            _returnModel = [ReturnCarModel mj_objectWithKeyValues:obj[@"data"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableview reloadData];
            });
        }
        else
        {
            
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        
    }];
}

- (void)requestUserInfor
{
    WEAKSELF;
    [HYBaseHandler requestWithTheFormUrl:SERVER_personal Parmers:nil Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            _model = [UserAccountModel mj_objectWithKeyValues:obj[@"data"]];
            UserAccountModel *userModel = [UserAccountModel shareMange];
            [userModel jsonUserData:obj];
            if (_model.type == 2)
            {
                [weakSelf requestTruckLineMine];
            }
            if (_model.type == 0)
            {
                if ([_model.appOpenId isEqualToString:@""])
                {
                    _titAry = @[@"",@"发布管理",@"钱包",@"设置",@"绑定微信"];
                    _imageAry = @[@"",@"my_sort01",@"my_sort04",@"my_sort05",@"wxin"];
                }
                else
                {
                    _titAry = @[@"",@"发布管理",@"钱包",@"设置"];
                    _imageAry = @[@"",@"my_sort01",@"my_sort04",@"my_sort05"];
                }
            }
            else if (_model.type == 1)
            {
                if ([_model.appOpenId isEqualToString:@""])
                {
                    _titAry = @[@"",@"发布管理",@"线路管理",@"店铺装修",@"钱包",@"设置",@"绑定微信"];
                    _imageAry = @[@"",@"my_sort01",@"my_sort02",@"my_sort03",@"my_sort04",@"my_sort05",@"wxin"];
                }
                else
                {
                    _titAry = @[@"",@"发布管理",@"线路管理",@"店铺装修",@"钱包",@"设置"];
                    _imageAry = @[@"",@"my_sort01",@"my_sort02",@"my_sort03",@"my_sort04",@"my_sort05"];
                }
            }
            else if (_model.type == 2)
            {
                if ([_model.appOpenId isEqualToString:@""])
                {
                    _titAry = @[@"",@"发布管理",@"我的货车",@"钱包",@"设置",@"绑定微信"];
                    _imageAry = @[@"",@"my_sort01",@"my_sort08",@"my_sort04",@"my_sort05",@"wxin"];
                }
                else
                {
                    _titAry = @[@"",@"发布管理",@"我的货车",@"钱包",@"设置"];
                    _imageAry = @[@"",@"my_sort01",@"my_sort08",@"my_sort04",@"my_sort05"];
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableview reloadData];
            });
        }
        else
        {
            if ([obj[@"code"] integerValue] == 444)
            {
                [LTools storage:NO ForKey:SERVER_IsLogin];
                LoginViewController *loginVC = [[LoginViewController alloc] init];
                //nav化
                HYNavBaseViewController *navVC = [[HYNavBaseViewController alloc] initWithRootViewController:loginVC];
                [self presentViewController:navVC animated:YES completion:nil];
                return;
            }
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
